package me.qi.kancha.security;

import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;
import org.springframework.stereotype.Component;

/**
 * @author sun
 * @date 2021/12/27 17:09
 * @modified By：
 */
@Component
public class ExceptionTranslator extends DefaultWebResponseExceptionTranslator {

    @Override
    public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
        // 异常重新构建防止匿名内部类
        if (OAuth2Exception.class.isAssignableFrom(e.getClass())) {
            OAuth2Exception exception = (OAuth2Exception) e;
            return super.translate(new OAuth2ExceptionEntity(exception));
        }
        return super.translate(e);
    }

    public static class OAuth2ExceptionEntity extends OAuth2Exception {
        private int httpErrorCode;
        private String oAuth2ErrorCode;
        public OAuth2ExceptionEntity(OAuth2Exception e) {
            super(e.getMessage());
            this.httpErrorCode = e.getHttpErrorCode();
            this.oAuth2ErrorCode = e.getOAuth2ErrorCode();
        }
        @Override
        public String getOAuth2ErrorCode() {
            return this.oAuth2ErrorCode;
        }
        @Override
        public int getHttpErrorCode() {
            return this.httpErrorCode;
        }
    }


}
